﻿using System;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using THS.HtmlHelpers;
using Veteran_cms.Models;

namespace Veteran_cms.Controllers
{
    public class ManageEventController : BaseController
    {
        readonly Veterandb _ctx = new Veterandb();
        //
        // GET: /ManageAbout/
        const int PageSize = 6;
        public ActionResult IndexEvents(int page = 1)
        {
            var model = new HomeAdminListViewModel();
            var events = _ctx.events.OrderByDescending(p => p.event_id).ToList();
            model.Events = events.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.EventPageInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = events.Count() };
            return View(model);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="page"></param>
        /// <returns></returns>
        public ActionResult Paging(int page = 1)
        {
            var model = new HomeAdminListViewModel();
            var events = _ctx.events.OrderByDescending(p => p.event_id).ToList();
            model.Events = events.Skip((page - 1) * PageSize).Take(PageSize).ToList();
            model.NewsArticlePageInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = PageSize, TotalItems = events.Count() };
            return PartialView("UCEventList", model);
        }

        public ActionResult Details(int id)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            var evt = _ctx.events.SingleOrDefault(c => c.event_id == id);
            if (evt != null)
            {
                return View(evt);
            }
            evt = new @event();
            return View(evt);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Details(int id, HttpPostedFileBase uploadFile)
        {
            try
            {
                // TODO: Add update logic here
                // if (!IsAuthenticateAdmin())
                //   return RedirectToAction("LogOn", "AdminHome");
                var oldImage = string.Empty;
                var oldThumbImage = string.Empty;
                var evt = _ctx.events.SingleOrDefault(p => p.event_id == id);
                if (uploadFile != null)
                {
                    if (evt != null && evt.event_id > 0)
                    {
                        oldImage = evt.image_large;
                        oldThumbImage = evt.image_thumbnail;
                    }
                    var fileName = Path.GetFileName(uploadFile.FileName);
                    var sFileName = GenerateFileNameByNo(Request, Utilities.VirtualPath, fileName, DateTime.Now.ToString("yyyyMMddhhmmss"));
                    var filePath = Path.Combine(Request.MapPath(Utilities.VirtualPath), sFileName);
                    var fileThumbPath = Path.Combine(Request.MapPath(Utilities.VirtualPath + "Thumbs/"), sFileName);
                    ResizeImage(uploadFile.InputStream, fileThumbPath, 99, 99, true);
                    ResizeImage(uploadFile.InputStream, filePath, 400, 300, true);
                    if (evt != null)
                    {
                        evt.image_large = Utilities.PhysicalPath + sFileName;
                        evt.image_thumbnail = String.Format("{0}Thumbs/{1}", Utilities.PhysicalPath, sFileName);
                    }
                }
                UpdateModel(evt);
                _ctx.SaveChanges();
                DeleteFile(Request, Utilities.VirtualPath, oldImage);

                DeleteFile(Request, Utilities.VirtualPath + "Thumbs", oldThumbImage);
                ViewData["Msg"] = "Đã cập nhật!";
                return View(evt);
            }
            catch
            {
                ViewData["Msg"] = "Đã có lỗi xẩy ra. Vui lòng kiểm tra lại dữ liệu!";
                return View();
            }
        }

        public ActionResult Delete(int id)
        {
            // TODO: Add delete logic here
            //if (!IsAuthenticateAdmin())
            //    return RedirectToAction("LogOn", "AdminHome");
            if (id <= 0)
                return RedirectToAction("Create", "ManageEvent", new @event());
            var evt = _ctx.events.SingleOrDefault(p => p.event_id == id);
            _ctx.DeleteObject(evt);
            _ctx.SaveChanges();
            if (evt != null)
            {
                DeleteFile(Request, Utilities.VirtualPath, evt.image_large);
                DeleteFile(Request, Utilities.VirtualPath + "Thumbs", evt.image_thumbnail);
            }
            return RedirectToAction("IndexEvents");
        }

        public ActionResult Create()
        {
            var evt = new @event { event_date = DateTime.Now.Date};
            return View(evt);
        }

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create([Bind(Exclude = "event_id")]@event evt, HttpPostedFileBase uploadFile)
        {
            // TODO: Add update logic here
            // if (!IsAuthenticateAdmin())
            //   return RedirectToAction("LogOn", "AdminHome");
            try
            {
                if (uploadFile != null)
                {
                    var fileName = Path.GetFileName(uploadFile.FileName);
                    var sFileName = GenerateFileNameByNo(Request, Utilities.VirtualPath, fileName, DateTime.Now.ToString("yyyyMMddhhmmss"));
                    var filePath = Path.Combine(Request.MapPath(Utilities.VirtualPath), sFileName);
                    var fileThumbPath = Path.Combine(Request.MapPath(Utilities.VirtualPath + "Thumbs/"), sFileName);
                    ResizeImage(uploadFile.InputStream, fileThumbPath, 99, 99, true);
                    ResizeImage(uploadFile.InputStream, filePath, 400, 300, true);
                    evt.image_large = Utilities.PhysicalPath + sFileName;
                    evt.image_thumbnail = String.Format("{0}Thumbs/{1}", Utilities.PhysicalPath, sFileName);
                }
                evt.created_date = DateTime.Now;
                _ctx.AddToevents(evt);
                _ctx.SaveChanges();
                ViewData["Msg"] = "Đã tạo thành công!";
                return RedirectToAction("IndexEvents");
            }
            catch
            {
                ViewData["Msg"] = "Đã có lỗi xẩy ra. Vui lòng kiểm tra lại dữ liệu!";
                return View(string.Empty);
            }
        }
        public void AllowVisible(int id)
        {
            //if (!IsAuthenticateAdmin())
            //    return;
            var evt = _ctx.events.SingleOrDefault(p => p.event_id == id);
            if (evt != null && evt.visible)
                evt.visible = false;
            else if (evt != null) evt.visible = true;
            _ctx.SaveChanges();
        }
    }
}
